package com.demo.controller;


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.demo.config.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
 * WebSocketController
 * @author zhengkai.blog.csdn.net
 */
@RestController
public class DemoController {

    public Log log = LogFactory.get(this.getClass());

    @GetMapping("index")
    public ResponseEntity<String> index(){
        return ResponseEntity.ok("请求成功");
    }

    @GetMapping("client1")
    public ModelAndView client1(){
        return new ModelAndView("client1");
    }

    @GetMapping("client2")
    public ModelAndView client2(){
        return new ModelAndView("client2");
    }

    @GetMapping("server")
    public ModelAndView server(){
        return new ModelAndView("server");
    }

    @RequestMapping("/push")
    public ResponseEntity<String> pushToWeb(String message, String toUserId) throws IOException {
        message = "Hello client " + (StringUtils.isNotBlank(toUserId) ? toUserId : "all") + ", This is server. The message content is " + message;
        log.info("服务器端推送消息：" + message);
        String sendInfo = WebSocketServer.sendInfo(message, toUserId);
        if(sendInfo==null) {
            sendInfo = "message send success";
        }
        return ResponseEntity.ok(sendInfo);
    }
}
